<script setup lang="ts">
import { onLoad } from '@dcloudio/uni-app'
import { ref, onMounted } from 'vue'
import { getPublickDataApi, getCodeRegistAPI } from '@/api/global'
import { baseURL } from '@/utils/http'
import Close from '@/components/close.vue'
import { postBusinessAPI, putBusinessAPI } from '@/api/business'
import type { ApplyBusiness } from '@/types/business'
import { useMemberStore } from '../../stores/modules/member'
import { getBusinessInfoByUseridAPI } from '@/api/business'
// import QQMapWX from '@/utils/qqmap-wx-jssdk'
import { getArea, getDistance } from '@/utils/utils'
import {useRoleStore} from '@/stores'
import {busListStore} from '@/stores'

const businessType = [
  { id: 'bus_user', label: '商家', value: 'bus_user' },
  { id: 'agent_user', label: '代理商', value: 'agent_user' },
  { id: 'bus_agent', label: '业代', value: 'bus_agent' },
]
const form = ref<ApplyBusiness>({
  type: '',
  typeName: '',
  imageUrl: '',
  agencyFee: '',
  name: '',
  shortName: '',
  industry: '',
  address: '',
  contacts: '',
  idCard: '',
  frontCardImage: '',
  backCardImage: '',
  businessLicense: '',
  businessLicenseUrl: '',
  contactsPhone: '',
  code: '',
  areaName: '',
  areaCode: '',
  appUserId: undefined,
  mobileCode: '',
})

// 获取页面参数
const query = defineProps<{
  id: string
}>()

// 获取企业信息
const getCompanyInfo = async () => {
  const res = await getBusinessInfoByUseridAPI(query.id)
  form.value = res.data
}

onMounted(() => {
  const title = query.id ? '修改信息' : '入驻'
  uni.setNavigationBarTitle({
    title: title,
  })
  getPublickAgency()
  if (query.id) {
    getCompanyInfo()
  }
})

// 获取代理费
const getPublickAgency = async () => {
  const res = await getPublickDataApi('AGENCY_FEE')
  form.value.agencyFee = res.data
}

// 修改城市
const onFullLocationChange: UniHelper.RegionPickerOnChange = (ev) => {
  // 修改前端界面
  form.value.areaName = ev.detail.value.join(' ')

  // 提交后端更新
  form.value.areaCode = ev.detail.code!.join(',')
}

// 修改类型
const onChangeType: UniHelper.RegionPickerOnChange = (ev) => {
  form.value.type = businessType[Number(ev.detail.value)].value
  form.value.typeName = businessType[Number(ev.detail.value)].label
}

// 修改图片
const onAvatarChange = (type: string) => {
  // 调用拍照/选择图片
  uni.chooseMedia({
    // 文件个数
    count: 1,
    // 文件类型
    mediaType: ['image'],
    success: (res) => {
      // 本地路径
      const { tempFilePath } = res.tempFiles[0]
      // 文件上传
      uni.uploadFile({
        url: '/admin/sys-file/upload',
        name: 'file', // 后端数据字段名
        filePath: tempFilePath, // 新头像
        success: (res) => {
          // 判断状态码是否上传成功
          if (res.statusCode === 200) {
            // 提取图片地址
            const { url } = JSON.parse(res.data).data
            // 当前页面更新图片信息
            if (type == 'license') {
              form.value!.businessLicenseUrl = url
            }
            if (type == 'frontCard') {
              form.value!.frontCardImage = url
            }
            if (type == 'backCard') {
              form.value!.backCardImage = url
            }
            if (type == 'imageUrl') {
              form.value!.imageUrl = url
            }
            uni.showToast({ icon: 'success', title: '上传成功' })
          } else {
            uni.showToast({ icon: 'error', title: '出现错误' })
          }
        },
      })
    },
  })
}

// 删除图片
const clearImg = (type: string) => {
  if (type == 'license') {
    form.value!.businessLicenseUrl = ''
  }
  if (type == 'frontCard') {
    form.value!.frontCardImage = ''
  }
  if (type == 'backCard') {
    form.value!.backCardImage = ''
  }
  if (type == 'imageUrl') {
    form.value!.imageUrl = ''
  }
  uni.showToast({ icon: 'success', title: '删除成功' })
}

const getLocation = () => {
  uni.getSystemInfo({
    success(res) {
      let locationEnabled = res.locationEnabled //判断手机定位服务是否开启
      let locationAuthorized = res.locationAuthorized //判断定位服务是否允许微信授权
      if (locationEnabled == false || locationAuthorized == false) {
        //手机定位服务（GPS）未授权
        uni.showModal({
          title: '授权',
          content: '获取授权失败，是否前往授权？',
          success: function (result) {
            if (result.confirm) {
              uni.openAppAuthorizeSetting()
            }
          },
          fail: function () {
            uni.showToast({
              title: '请前往设置中授权位置信息',
              icon: 'none',
            })
          },
        })
      } else {
        uni.chooseLocation({
          success: function (response) {
            form.value.address = response.address
            if (response.address) {
              // 获取详细信息后，分割出省市县
              const extractAddress = getArea(response.address)
              // [省，市，县，详细地址]
              // userInfo.areaProvince = extractAddress.shift()
              // userInfo.areaCity = extractAddress.shift()
              // userInfo.areaRegion = extractAddress.shift()
              // userInfo.areaInfo = extractAddress.join('') //详细地址
            }
            form.value.lat = response.latitude.toString()
            form.value.lng = response.longitude.toString()
            let la1 = response.latitude
            let lo1 = response.longitude
            const dis = getDistance(la1, lo1, 39.85856, 116.28616)
          },
        })
      }
    },
  })
}

// 获取表单组件实例，用于调用表单方法
const formRef = ref<UniHelper.UniFormsInstance>()

// 定义校验规则
const rules: UniHelper.UniFormsRules = {
  typeName: {
    rules: [{ required: true, errorMessage: '请选择入驻类型' }],
  },
  name: {
    rules: [{ required: true, errorMessage: '请输入公司名称' }],
  },
  type: {
    rules: [{ required: true, errorMessage: '请选择入驻类型' }],
  },
  businessLicense: {
    rules: [{ required: true, errorMessage: '请输入营业执照号' }],
  },
  businessLicenseUrl: {
    rules: [{ required: true, errorMessage: '请上传营业执照' }],
  },
  industry: {
    rules: [{ required: true, errorMessage: '请输入所属行业' }],
  },
  areaName: {
    rules: [{ required: true, errorMessage: '请选择城市' }],
  },
  address: {
    rules: [{ required: true, errorMessage: '请获取当前定位信息' }],
  },
  contacts: {
    rules: [{ required: true, errorMessage: '请输入负责人姓名' }],
  },
  idCard: {
    rules: [
      { required: true, errorMessage: '请输入身份证号' },
      {
        pattern:
          /^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/,
        errorMessage: '身份证号格式不正确',
      },
    ],
  },
  frontCardImage: {
    rules: [{ required: true, errorMessage: '请上传身份证正面' }],
  },
  backCardImage: {
    rules: [{ required: true, errorMessage: '请上传身份证背面' }],
  },
  contactsPhone: {
    rules: [
      { required: true, errorMessage: '请输入负责人电话号码' },
      { pattern: /^1[3-9]\d{9}$/, errorMessage: '手机号格式不正确' },
    ],
  },
  mobileCode: {
    rules: [{ required: true, errorMessage: '请输入验证码' }],
  },
}

// 获取验证码
const count = ref(60)
const counting = ref(false)
const getCode = ref('')

const getCodeRegist = async () => {
  if (form.value.contactsPhone) {
    const res = await getCodeRegistAPI(form.value.contactsPhone)
    if (res.code == '0') {
      getCode.value = res.msg
      uni.showToast({
        icon: 'none',
        title: '验证码发送成功，请查看手机短信！',
      })
    } else {
      uni.showToast({
        icon: 'none',
        title: res.msg,
      })
    }
    counting.value = true
    const timer = setInterval(() => {
      count.value--
      if (count.value <= 0) {
        clearInterval(timer)
        counting.value = false
        count.value = 60 // 重置倒计时时长
      }
    }, 1000)
  } else {
    uni.showToast({
      icon: 'none',
      title: '请输入手机号',
    })
  }
}

const roleStore = useRoleStore()
const busStore = busListStore()

// 提交表单信息
const memberStore = useMemberStore()
const onSubmit = async () => {
  // 已登录，可以提交信息
  if (memberStore.profile.userId) {
    try {
      // 表单校验
      await formRef.value?.validate?.()
      // 校验通过后再发送请求
      // 修改信息
      if (query.id) {
        uni.showLoading({
          title: '提交中...',
          mask: true,
        })
        const res = await putBusinessAPI(form.value)
        uni.hideLoading()
        uni.showToast({ icon: 'success', title: res.msg })
      } else {
        // 提交新增
        form.value.appUserId = memberStore.profile.userId
        uni.showLoading({
          title: '提交中...',
          mask: true,
        })
        const res = await postBusinessAPI(form.value)
        uni.hideLoading()
        uni.showToast({
          icon: 'none',
          title: res.code == '0' ? '入驻操作已完成，请耐心等待平台审核' : res.msg,
        })
        if (res.code == '0') {
          memberStore.clearProfile()
          roleStore.clearRoles()
          busStore.clearBus()
          setTimeout(() => {
            uni.redirectTo({ url: '/pages/index/index' })
          }, 1000)
        }
      }
    } catch (error) {
      uni.showToast({ icon: 'error', title: '请填写完整信息' })
    }
  } else {
    uni.showToast({ icon: 'success', title: '您还没有登录，请登录后再申请' })
    setTimeout(() => {
      uni.redirectTo({ url: '/pages/login/login' })
    }, 500)
  }
}
</script>

<template>
  <view class="profile"> 欢迎入驻暖城乐促 </view>
  <!-- 表单 -->
  <view class="form">
    <!-- 表单内容 -->
    <uni-forms :rules="rules" :model="form" ref="formRef" class="form-content">
      <uni-forms-item name="typeName" class="form-item">
        <text class="label">入驻类型</text>
        <picker
          class="picker"
          mode="selector"
          :value="form?.type"
          :range="businessType"
          :range-key="'label'"
          @change="onChangeType"
        >
          <view v-if="form?.typeName">{{ form?.typeName }}</view>
          <view class="placeholder" v-else style="color: #999">请选择</view>
        </picker>
      </uni-forms-item>
      <!-- <view class="form-item" v-if="form?.type == 'agent_user'" style="padding-top: 0"
        >代理商入驻需要支付代理费：{{ form.agencyFee }}元</view
      > -->
      <view class="form-item" v-if="form?.type == 'agent_user'" style="padding-top: 0"
        >代理商入驻在此处完成操作后，需要缴纳代理费方可完成入驻，具体事宜联系：153 2693 6179</view
      >
      <template v-if="form?.type == 'bus_user'">
        <uni-forms-item name="name" class="form-item">
          <text class="label">公司名称</text>
          <input class="input" type="text" placeholder="请填写" v-model="form.name" />
        </uni-forms-item>
        <uni-forms-item class="form-item">
          <text class="label">公司简称</text>
          <input class="input" type="text" placeholder="请填写" v-model="form.shortName" />
        </uni-forms-item>
        <!-- <view class="form-item image_upload">
          <text class="label">公司照片</text>
          <view v-if="!form.imageUrl" class="upload" @tap="onAvatarChange('imageUrl')">
            <uni-icons type="plusempty" color="#ddd" size="40" />
          </view>
          <view v-else class="company_img">
            <image :src="baseURL + form.imageUrl" mode="aspectFill" />
            <Close @tap="clearImg('imageUrl')"></Close>
          </view>
        </view> -->
        <uni-forms-item name="businessLicense" class="form-item">
          <text class="label">营业执照号</text>
          <input class="input" type="text" placeholder="请填写" v-model="form.businessLicense" />
        </uni-forms-item>
        <uni-forms-item name="businessLicenseUrl" class="form-item image_upload">
          <text class="label">营业执照</text>
          <view v-if="!form.businessLicenseUrl" class="upload" @tap="onAvatarChange('license')">
            <uni-icons type="plusempty" color="#ddd" size="40" />
          </view>
          <view v-else class="company_img">
            <image :src="baseURL + form.businessLicenseUrl" mode="aspectFill" />
            <Close @tap="clearImg('license')"></Close>
          </view>
        </uni-forms-item>
        <uni-forms-item name="industry" lass="form-item">
          <text class="label">所属行业</text>
          <input class="input" type="text" placeholder="请填写" v-model="form.industry" />
        </uni-forms-item>
      </template>

      <uni-forms-item name="areaName" class="form-item">
        <text class="label">{{ form?.type == 'bus_user' ? '城市' : '代理地区' }}</text>
        <picker
          class="picker"
          mode="region"
          :value="form.areaName?.split(' ') || ''"
          @change="onFullLocationChange"
        >
          <view v-if="form.areaName">{{ form.areaName }}</view>
          <view class="placeholder" v-else style="color: #999">请选择城市</view>
        </picker>
      </uni-forms-item>
      <uni-forms-item name="address" class="form-item">
        <text class="label">常住地址</text>
        <input
          class="input"
          type="text"
          placeholder="点击获取当前定位信息"
          v-model="form.address"
          @tap="getLocation"
        />
      </uni-forms-item>
      <uni-section title="实名认证" type="line" v-if="form.type != 'bus_agent'">
        <uni-forms-item name="contacts" class="form-item">
          <text class="label">负责人姓名</text>
          <input class="input" type="text" placeholder="请填写" v-model="form.contacts" />
        </uni-forms-item>
        <uni-forms-item name="idCard" class="form-item">
          <text class="label">身份证号</text>
          <input class="input" maxlength="18" placeholder="请填写" v-model="form.idCard" />
        </uni-forms-item>
        <uni-forms-item name="frontCardImage" class="form-item image_upload">
          <text class="label">身份证正面</text>
          <view v-if="!form.frontCardImage" class="upload" @tap="onAvatarChange('frontCard')">
            <uni-icons type="plusempty" color="#ddd" size="40" />
          </view>
          <view v-else class="company_img">
            <image :src="baseURL + form.frontCardImage" mode="aspectFill" />
            <Close @tap="clearImg('frontCard')"></Close>
          </view>
        </uni-forms-item>
        <uni-forms-item name="backCardImage" class="form-item image_upload">
          <text class="label">身份证背面</text>
          <view v-if="!form.backCardImage" class="upload" @tap="onAvatarChange('backCard')">
            <uni-icons type="plusempty" color="#ddd" size="40" />
          </view>
          <view v-else class="company_img">
            <image :src="baseURL + form.backCardImage" mode="aspectFill" />
            <Close @tap="clearImg('backCard')"></Close>
          </view>
        </uni-forms-item>
      </uni-section>
      <uni-forms-item name="contactsPhone" class="form-item">
        <text class="label">电话号码</text>
        <input
          class="input phone_input"
          type="text"
          placeholder="请填写"
          v-model="form.contactsPhone"
        />
        <button class="code send" style="width: 100px;" :disabled="counting" @tap="getCodeRegist">{{ counting ? `${count}秒后重新获取` : '获取验证码' }}</button>
      </uni-forms-item>
      <uni-forms-item name="mobileCode" class="form-item">
        <text class="label">验证码</text>
        <input class="input" type="text" placeholder="请填写" v-model="form.mobileCode" />
      </uni-forms-item>
    </uni-forms>
    <view class="tongyi">
      <!-- <radio
        value="agreement"
        color="#27ba9b"
        :checked="agreement"
        style="transform: scale(0.7)"
      /> -->
      提交申请即视为你已阅读并同意<navigator
        url="/pages/newsDetail/newsDetail?id=1751203528382128130"
      >
        <text style="color: rgb(0, 184, 246);">《入驻协议》</text>
      </navigator>
    </view>
    <!-- 提交按钮 -->
    <button class="form-button" @tap="onSubmit">提交入驻信息</button>
  </view>
</template>

<style lang="scss">
.form {
  height: auto;
  padding-bottom: 20px;
  padding: 20px;
  background-color: #fff;
}
.profile {
  padding: 60rpx 0 60rpx;
  position: relative;
  background-color: rgb(0, 206, 170);
  color: #fff;
  text-align: center;
}
.upload {
  width: 300rpx;
  height: 200rpx;
  border: 1px solid #ddd;
  border-radius: 10rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  padding-top: 10rpx;
}
.phone_input {
  width: calc(100% - 190px);
}
.send {
  width: 100px;
  padding: 0;
}
</style>
